<template>
  <view class="auth-container">
    <!-- 页面标题 -->
    <view class="header">
      <view class="wifi-icon">📶</view>
      <view class="title">WiFi连接认证</view>
      <view class="subtitle">请完成微信授权以连接网络</view>
    </view>
    
    <!-- 认证状态区域 -->
    <view class="auth-content">
      <!-- 等待授权状态 -->
      <view v-if="authStatus === 'waiting'" class="auth-waiting">
        <view class="auth-avatar">
          <image src="/static/images/profile.jpg" class="default-avatar" />
        </view>
        <view class="auth-tips">点击下方按钮获取微信授权</view>
        <button class="auth-btn" @tap="handleAuthClick">
          <view class="btn-icon">🔐</view>
          <text>微信授权登录</text>
        </button>
        
        <!-- 测试按钮 -->
        <button class="test-auth-btn" @tap="testWechatAPI" style="margin-top: 30rpx;">
          <text>测试微信API</text>
        </button>
      </view>
      
      <!-- 认证处理中状态 -->
      <view v-if="authStatus === 'processing'" class="auth-processing">
        <view class="auth-avatar">
          <image :src="userInfo.avatarUrl" class="user-avatar" v-if="userInfo.avatarUrl" />
        </view>
        <view class="processing-animation">
          <view class="loading-indicator">{{ loadingText }}</view>
        </view>
        <view class="auth-tips">{{ userInfo.nickName }}，正在为您连接网络...</view>
        <view class="progress-info">
          <text class="progress-text">认证进度：{{ progressText }}</text>
          <progress :percent="progressPercent" stroke-width="6" activeColor="#1890ff" />
        </view>
      </view>
      
      <!-- 认证失败状态 -->
      <view v-if="authStatus === 'failed'" class="auth-failed">
        <view class="status-icon error">❌</view>
        <view class="status-title">认证失败</view>
        <view class="status-message">{{ errorMessage }}</view>
        <button class="retry-btn" @tap="retryAuth">重新认证</button>
      </view>
    </view>
    
    <!-- 底部说明 -->
    <view class="footer">
      <view class="tips">
        <text>• 我们仅获取您的基本信息用于网络认证</text>
        <text>• 认证完成后即可正常使用网络</text>
        <text>• 如有问题请联系网络管理员</text>
      </view>
    </view>
  </view>
</template>

<script>
import { wechatAuth, checkAuthStatus } from '@/api/wifi/auth'

export default {
  name: 'WifiAuth',
  data() {
    return {
      deviceId: '',
      sessionId: '',
      authStatus: 'waiting', // waiting, processing, failed
      userInfo: {},
      progressPercent: 0,
      progressText: '准备中...',
      errorMessage: '',
      statusTimer: null,
      loadingText: {
        contentdown: '上拉显示更多',
        contentrefresh: '正在加载...',
        contentnomore: '没有更多数据了'
      }
    }
  },
  onLoad(options) {
    console.log('Auth页面参数：', options)
    this.deviceId = options.deviceId || ''
    this.sessionId = options.sessionId || ''
    
    if (!this.deviceId || !this.sessionId) {
      uni.showToast({
        title: '参数错误',
        icon: 'error'
      })
      return
    }
  },
  onUnload() {
    if (this.statusTimer) {
      clearInterval(this.statusTimer)
    }
  },
  methods: {
    // 处理授权按钮点击
    handleAuthClick() {
      console.log('微信授权按钮被点击')
      console.log('当前参数:', {
        deviceId: this.deviceId,
        sessionId: this.sessionId,
        authStatus: this.authStatus
      })
      
      // 检查必要参数
      if (!this.deviceId || !this.sessionId) {
        console.error('缺少必要参数')
        uni.showToast({
          title: '参数错误，请重新进入',
          icon: 'error'
        })
        return
      }
      
      // 显示加载提示
      uni.showToast({
        title: '正在授权...',
        icon: 'loading',
        duration: 2000
      })
      
      // 调用授权方法
      this.getUserProfile()
    },
    
    // 测试微信API
    testWechatAPI() {
      console.log('测试微信API')
      
      uni.showModal({
        title: '测试微信API',
        content: '测试微信登录接口是否可用',
        success: (res) => {
          if (res.confirm) {
            // 测试微信登录
            uni.login({
              provider: 'weixin',
              success: (loginRes) => {
                console.log('微信登录测试成功：', loginRes)
                uni.showModal({
                  title: '测试结果',
                  content: `微信登录成功！\ncode: ${loginRes.code}`,
                  showCancel: false
                })
              },
              fail: (error) => {
                console.error('微信登录测试失败：', error)
                uni.showModal({
                  title: '测试结果',
                  content: `微信登录失败：${JSON.stringify(error)}`,
                  showCancel: false
                })
              }
            })
          }
        }
      })
    },
    
    // 获取用户授权
    getUserProfile() {
      const self = this
      
      console.log('开始微信授权流程')
      
      // 先获取微信登录code
      uni.login({
        provider: 'weixin',
        success: (loginRes) => {
          console.log('微信登录成功：', loginRes)
          
          // 尝试获取用户信息
          uni.getUserInfo({
            provider: 'weixin',
            success: (userRes) => {
              console.log('获取用户信息成功：', userRes)
              self.userInfo = userRes.userInfo
              self.submitWechatAuth(loginRes.code)
            },
            fail: (userError) => {
              console.log('获取用户信息失败，尝试getUserProfile：', userError)
              
              // 如果getUserInfo失败，尝试getUserProfile（兼容旧版本）
              if (uni.getUserProfile) {
                uni.getUserProfile({
                  desc: '用于WiFi网络认证',
                  success: (profileRes) => {
                    console.log('getUserProfile成功：', profileRes)
                    self.userInfo = profileRes.userInfo
                    self.submitWechatAuth(loginRes.code)
                  },
                  fail: (profileError) => {
                    console.error('getUserProfile失败：', profileError)
                    // 即使获取用户信息失败，也继续授权流程，使用默认信息
                    self.userInfo = {
                      nickName: '微信用户',
                      avatarUrl: '/static/images/profile.jpg'
                    }
                    self.submitWechatAuth(loginRes.code)
                  }
                })
              } else {
                // 如果都不支持，使用默认信息继续流程
                console.log('使用默认用户信息继续流程')
                self.userInfo = {
                  nickName: '微信用户',
                  avatarUrl: '/static/images/profile.jpg'
                }
                self.submitWechatAuth(loginRes.code)
              }
            }
          })
        },
        fail: (error) => {
          console.error('微信登录失败：', error)
          uni.showToast({
            title: '微信登录失败，请重试',
            icon: 'error'
          })
        }
      })
    },
    
    // 提交微信认证
    async submitWechatAuth(code) {
      try {
        this.authStatus = 'processing'
        this.progressText = '提交认证信息...'
        this.progressPercent = 20
        
        const authData = {
          sessionId: this.sessionId,
          code: code,
          deviceId: this.deviceId,
          userInfo: this.userInfo
        }
        
        console.log('提交认证数据：', authData)
        const response = await wechatAuth(authData)
        
        if (response.code === 200) {
          this.progressText = '认证提交成功，等待处理...'
          this.progressPercent = 50
          
          // 开始轮询认证状态
          this.startStatusPolling()
        } else {
          throw new Error(response.msg || '认证提交失败')
        }
      } catch (error) {
        console.error('提交认证失败：', error)
        this.authStatus = 'failed'
        this.errorMessage = error.message || '认证提交失败，请重试'
      }
    },
    
    // 开始状态轮询
    startStatusPolling() {
      let pollCount = 0
      const maxPolls = 30 // 最多轮询30次（60秒）
      
      this.statusTimer = setInterval(async () => {
        try {
          pollCount++
          this.progressText = `正在认证中... (${pollCount}/${maxPolls})`
          this.progressPercent = 50 + (pollCount / maxPolls) * 40
          
          const response = await checkAuthStatus(this.sessionId)
          
          if (response.code === 200) {
            const status = response.data.status
            
            if (status === 'success') {
              // 认证成功
              clearInterval(this.statusTimer)
              this.progressPercent = 100
              this.progressText = '认证成功！'
              
              setTimeout(() => {
                this.goToPhonePage()
              }, 1000)
              
            } else if (status === 'failed') {
              // 认证失败
              clearInterval(this.statusTimer)
              this.authStatus = 'failed'
              this.errorMessage = response.data.message || '网络认证失败'
              
            } else if (pollCount >= maxPolls) {
              // 超时
              clearInterval(this.statusTimer)
              this.authStatus = 'failed'
              this.errorMessage = '认证超时，请重试'
            }
          }
        } catch (error) {
          console.error('状态轮询失败：', error)
          if (pollCount >= maxPolls) {
            clearInterval(this.statusTimer)
            this.authStatus = 'failed'
            this.errorMessage = '网络连接失败，请重试'
          }
        }
      }, 2000)
    },
    
    // 重新认证
    retryAuth() {
      this.authStatus = 'waiting'
      this.userInfo = {}
      this.progressPercent = 0
      this.progressText = '准备中...'
      this.errorMessage = ''
      
      if (this.statusTimer) {
        clearInterval(this.statusTimer)
      }
    },
    
    // 跳转到手机号页面
    goToPhonePage() {
      uni.navigateTo({
        url: `/pages/wifi/phone/index?deviceId=${this.deviceId}&sessionId=${this.sessionId}&userInfo=${encodeURIComponent(JSON.stringify(this.userInfo))}`
      })
    },
    
    // 跳转到结果页
    goToResult(result) {
      uni.redirectTo({
        url: `/pages/wifi/result/index?result=${result}&deviceId=${this.deviceId}`
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.auth-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40rpx;
  display: flex;
  flex-direction: column;
}

.header {
  text-align: center;
  color: #fff;
  margin-bottom: 80rpx;
}

.wifi-icon {
  font-size: 120rpx;
  margin-bottom: 20rpx;
}

.title {
  font-size: 48rpx;
  font-weight: bold;
  margin-bottom: 16rpx;
}

.subtitle {
  font-size: 28rpx;
  opacity: 0.9;
}

.auth-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.auth-waiting, .auth-processing, .auth-failed {
  width: 100%;
  text-align: center;
  color: #fff;
}

.auth-avatar {
  margin-bottom: 40rpx;
}

.default-avatar, .user-avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 60rpx;
  border: 4rpx solid #fff;
}

.auth-tips {
  font-size: 32rpx;
  margin-bottom: 60rpx;
  opacity: 0.9;
}

.auth-btn {
  width: 500rpx;
  height: 88rpx;
  background: #fff;
  color: #333;
  border: none;
  border-radius: 44rpx;
  font-size: 32rpx;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  
  &::after {
    border: none;
  }
}

.btn-icon {
  margin-right: 16rpx;
  font-size: 28rpx;
}

.processing-animation {
  margin: 40rpx 0;
}

.loading-indicator {
  font-size: 28rpx;
  color: #1890ff;
  text-align: center;
  padding: 20rpx;
  position: relative;
  
  &::after {
    content: '';
    display: inline-block;
    width: 40rpx;
    height: 40rpx;
    border: 4rpx solid #e0e0e0;
    border-top-color: #1890ff;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-left: 16rpx;
    vertical-align: middle;
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.progress-info {
  width: 100%;
  margin-top: 40rpx;
}

.progress-text {
  display: block;
  font-size: 28rpx;
  margin-bottom: 16rpx;
  opacity: 0.9;
}

.status-icon {
  font-size: 120rpx;
  margin-bottom: 32rpx;
  
  &.error {
    color: #ff4757;
  }
}

.status-title {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 16rpx;
}

.status-message {
  font-size: 28rpx;
  margin-bottom: 40rpx;
  opacity: 0.9;
}

.retry-btn {
  width: 400rpx;
  height: 80rpx;
  background: #ff4757;
  color: #fff;
  border: none;
  border-radius: 40rpx;
  font-size: 30rpx;
  
  &::after {
    border: none;
  }
}

.test-auth-btn {
  width: 400rpx;
  height: 70rpx;
  background: transparent;
  color: #fff;
  border: 2rpx solid rgba(255, 255, 255, 0.5);
  border-radius: 35rpx;
  font-size: 28rpx;
  
  &::after {
    border: none;
  }
}

.footer {
  margin-top: 40rpx;
  color: #fff;
  opacity: 0.8;
}

.tips {
  font-size: 24rpx;
  line-height: 1.6;
  
  text {
    display: block;
    margin-bottom: 8rpx;
  }
}
</style> 